/*
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * $Id: LogMatcher.java 485 2007-02-18 16:43:48Z jacek.kolezynski $
 */
package logmatcher;

import java.io.IOException;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.configuration.CompositeConfiguration;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.SystemConfiguration;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.commons.configuration.XMLPropertiesConfiguration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import bsh.Capabilities;
import bsh.EvalError;
import bsh.Interpreter;


/**
 * Initializes all elements specified in configuration.
 *
 * @version $Revision: 485 $
*/
public class LogMatcher {
    //~ Static fields/initializers -----------------------------------------------------------------------------------

    /** Class logger. */
    private static final Log LOGGER = LogFactory.getLog(LogMatcher.class);

    //~ Constructors -------------------------------------------------------------------------------------------------

/**
     * Creates a new LogMatcher object.
     *
     * @param config configuration object.
     *
     * @throws InitializationException in case some of the system elements cannot be initialized.
     */
    public LogMatcher(Configuration config) throws InitializationException {
        configure(config);
    }

    //~ Methods ------------------------------------------------------------------------------------------------------

    /**
     * Main function, pretends the library is an application.
     *
     * @param args startup arguments.
     */
    public static void main(String[] args) {
        LOGGER.info("Starting LogMatcher...");

        try {
            CompositeConfiguration config = new CompositeConfiguration();

            Option systemOpt = new Option("system", "add system properties to the program configuration");
            Option propertiesOpt = OptionBuilder.withArgName("file").hasArg()
                                                .withDescription("use given file as source of key-value pairs")
                                                .create("properties");
            Option xmlpropertiesOpt = OptionBuilder.withArgName("xmlfile").hasArg()
                                                   .withDescription(
                    "use given file as source of key-value pairs stored in XML").create("xmlprops");
            Option xmlOpt = OptionBuilder.withArgName("xmlfile").hasArg()
                                         .withDescription("parse given XML file to find kay-vlue pairs").create(
                    "xml");
            Option bshServerOpt = OptionBuilder.withArgName("port").hasOptionalArg()
                                               .withDescription("starts Bean Shell server on a specified port")
                                               .create("bshserver");
            Option bshConsoleOpt = new Option("bshconsole", "run graphical desktop for BeanShell");
            Option startOpt = new Option("start", "establish necessary connections and start collectors");
            Option helpOpt = new Option("help", "print help");

            Options options = new Options();
            options.addOption(systemOpt);
            options.addOption(xmlpropertiesOpt);
            options.addOption(xmlOpt);
            options.addOption(propertiesOpt);
            options.addOption(bshConsoleOpt);
            options.addOption(bshServerOpt);
            options.addOption(startOpt);
            options.addOption(helpOpt);

            CommandLineParser parser = new GnuParser();

            try {
                // parse the command line arguments
                CommandLine line = parser.parse(options, args);

                if (line.hasOption("help")) {
                    HelpFormatter formatter = new HelpFormatter();
                    formatter.printHelp("logmatcher [-options]", options);
                    System.exit(0);
                }

                if (line.hasOption("system")) {
                    config.addConfiguration(new SystemConfiguration());
                }

                if (line.hasOption("properties")) {
                    // initialise config from given file
                    config.addConfiguration(new PropertiesConfiguration(line.getOptionValue("properties")));
                } else if (line.hasOption("xmlprops")) {
                    // initialise config from given xml properties file
                    config.addConfiguration(new XMLPropertiesConfiguration(line.getOptionValue("xmlprops")));
                } else if (line.hasOption("xml")) {
                    // initialise config from given xml file
                    config.addConfiguration(new XMLConfiguration(line.getOptionValue("xml")));
                } else {
                    config.addConfiguration(new PropertiesConfiguration("logmatcher.properties"));
                }

                if (line.hasOption("bshconsole")) {
                    if (!Capabilities.classExists("bsh.util.Util")) {
                        LOGGER.warn("Can't find the BeanShell utilities...");
                    }

                    if (Capabilities.haveSwing()) {
                        bsh.util.Util.startSplashScreen();

                        Interpreter bshInterpreter = new Interpreter();

                        try {
                            bshInterpreter.set("configuration", config);
                            bshInterpreter.eval("setAccessibility(true)"); // turn off access restrictions
                            bshInterpreter.eval("desktop()");
                        } catch (EvalError e) {
                            LOGGER.error("Couldn't start desktop", e);
                        }
                    } else {
                        LOGGER.error(
                            "Can't find javax.swing package: "
                            + " An AWT based Console is available but not built by default.");
                    }
                }

                if (line.hasOption("bshserver")) {
                    String portN = line.getOptionValue("bshserver");
                    int port = (portN != null) ? Integer.parseInt(portN) : 1234;

                    if (portN != null) {
                        LOGGER.info("Starting BeanShell server on port=" + port);
                    } else {
                        LOGGER.debug("Starting BeanShell server on default port=" + port);
                    }

                    Interpreter bshInterpreter = new Interpreter();

                    try {
                        bshInterpreter.set("configuration", config);
                        bshInterpreter.set("portnum", port);
                        bshInterpreter.eval("setAccessibility(true)"); // turn off access restrictions

                        bshInterpreter.eval("server(portnum)");
                    } catch (EvalError e) {
                        LOGGER.error("Error while initialization of BeanShell", e);
                    }
                }

                new LogMatcher(config);

                if (line.hasOption("start")) {
                    String[] collectorNames = config.getStringArray("logmatcher.collectors");
                    LogEventListener eventListener = (LogEventListener)config.getProperty("logmatcher.logbuffer");

                    for (int i = 0; i < collectorNames.length; i++) {
                        Collector c = (Collector)config.getProperty("logmatcher.collectors." + collectorNames[i]);

                        if (c instanceof LogEventProducer) {
                            ((LogEventProducer)c).addLogEventListener(eventListener);
                        }

                        try {
                            c.start();
                        } catch (IOException e) {
                            LOGGER.error("Unable to start collector " + collectorNames[i]);
                        }
                    }

                    // TODO It should be initialized elsewhere.
                    LogEventProducer logBuffer = (LogEventProducer)config.getProperty("logmatcher.logbuffer");
                    String[] analyzerNames = config.getStringArray("logmatcher.collectors");

                    for (int i = 0; i < collectorNames.length; i++) {
                        LogEventListener l = (LogEventListener)config.getProperty(
                                "logmatcher.analyzers." + analyzerNames[i]);
                        logBuffer.addLogEventListener(l);
                    }
                }
            } catch (ParseException e) {
                LOGGER.error("Parsing of command line arguments failed.  Reason: " + e.getMessage());

                HelpFormatter formatter = new HelpFormatter();
                formatter.printHelp("logmatcher [-options]", options);
            }
        } catch (ConfigurationException e) {
            LOGGER.error("Unable to initialize configuration", e);
        } catch (InitializationException e) {
            LOGGER.error("Configuration contains incorrect values, unable to initialize objects", e);
        }
    }


    /**
     * Initialize all related elements: buffers, collectors, etc.
     *
     * @param config configuration object.
     */
    private void configure(Configuration config) {
        Utils.initElement(config, "logmatcher.logbuffer", LogEventProducer.class, true);
        Utils.initListOfElements(config, "logmatcher.filters", InputFilter.class, true);
        Utils.initListOfElements(config, "logmatcher.collectors", Collector.class, true);
        Utils.initListOfElements(config, "logmatcher.analyzers", LogEventListener.class, true);
    }
}
